let wechatUserId = $('#hiddenUserId').val();
let dataType = 2011;
let myChart = null;
let tempDataList = [];
let pageNum = 1;
let pageSize = 10;
let scrollContainer = document.getElementById('messageDiv');
let lastLoadStatus = true;

$(function () {
    if (null === wechatUserId || wechatUserId === '') {
        wechatUserId = sessionStorage.getItem('loginWeChatUserId');
    } else {
        sessionStorage.setItem('loginWeChatUserId', wechatUserId);
    }

    // 初始化选项卡
    initTabs();

    let defaultDataType = sessionStorage.getItem('selectDataType');

    if (null !== defaultDataType && !isNaN(defaultDataType)) {
        changeDataType(defaultDataType);
    } else {
        changeDataType(2011);
    }

    // 无限滚动
    $('.mainContent').on('scroll', function () {
        const scrollTop = scrollContainer.scrollTop;
        const scrollHeight = scrollContainer.scrollHeight;
        const clientHeight = scrollContainer.clientHeight;

        if (lastLoadStatus && (scrollTop + clientHeight >= scrollHeight - 50)) {
            lastLoadStatus = false;
            pageNum++;
            loadMessageList();
        }
    });
});

// 卡片点击效果
document.querySelectorAll('.data-card').forEach(card => {
    card.addEventListener('click', function () {
        this.style.transform = 'scale(0.98)';

        setTimeout(() => {
            this.style.transform = '';
        }, 200);

        // 这里可以添加卡片点击后的业务逻辑
    });
});

function changeDataType(type) {
    dataType = type;
    pageNum = 1;
    tempDataList = [];

    // 根据选中的数据类型自动改变样式
    changeTab(type);

    loadMessageList();
}

function loadMessageList() {
    showLoading();

    // 先根据公司ID和用户ID加载出所有的设备列表
    $.post(serverUrl + ':' + serverPort + serverName + '/alarmMessage/iPageByParams', {
        userId: wechatUserId, type: dataType, keyWord: $('#selectItem').val(), pageNum: pageNum, pageSize: pageSize
    }, function (result) {
        hideLoading();

        let obj = JSON.parse(result);

        if (obj.code === 0) {
            tempDataList = tempDataList.concat(obj.data.list);

            $('#messageDiv').html(createTableHtml(tempDataList));
        }

        lastLoadStatus = true;
    });
}

function createTableHtml(deviceDataList) {
    let content = '';

    $.each(deviceDataList, function (index, item) {
        // 创建卡片头部
        content += '<div class="data-card">';
        content += '<div class="card-header">';
        content += '<div class="device-name">' + item.companyName + ' - ' + item.deviceName + '</div>';
        content += '</div>';

        content += '<div class="data-row">';
        content += '<div class="data-item">';
        content += '<span>预警时间</span>';
        content += '<div class="data-value">' + formatTime(item.createTime) + '</div>';
        content += '</div>';

        if (!item.description.includes('设备') && !item.description.includes('数据功能')) {
            content += '<div class="data-item">';
            content += '<span>触发数值</span>';
            content += '<div class="data-value">' + item.num + '</div>';
            content += '</div>';
        }

        content += '</div>';

        if (!item.description.includes('设备') && !item.description.includes('数据功能')) {
            content += '<div class="data-row">';
            content += '<div class="data-item">';
            content += '<span>因子名称</span>';
            content += '<div class="data-value">' + item.codeDictName + '</div>';
            content += '</div>';
            content += '<div class="data-item">';
            content += '<span>因子单位</span>';
            content += '<div class="data-value">' + item.codeDictUnit + '</div>';
            content += '</div>';
            content += '</div>';
        }

        content += '<div class="data-row" style="grid-template-columns: none;">';
        content += '<div class="data-item" style="text-align: left;">';
        content += '<div class="data-value">' + item.description + '</div>';
        content += '</div>';
        content += '</div>';

        content += '</div>';
    });

    return content;
}

// 获取DOM元素
const userInput = document.getElementById('selectItem');

// 状态变量
let isComposing = false; // 用于检测中文输入状态
let lastValue = ''; // 上次保存的值

// 内容变化处理函数（防抖后）
function handleContentChange() {
    const currentValue = userInput.value;

    // 内容实际发生变化时才处理
    if (currentValue !== lastValue) {
        lastValue = currentValue;
        tempDataList = [];
        loadMessageList();
    }
}

// 创建防抖函数
function debounce(func, delay) {
    let timer;
    return function () {
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(this, arguments);
        }, delay);
    };
}

// 创建500ms防抖的内容变化处理器
const debouncedChangeHandler = debounce(handleContentChange, 500);

// 事件监听
userInput.addEventListener('input', function () {
    // 中文输入过程中不触发
    if (!isComposing) {
        debouncedChangeHandler();
    }
});

// 处理中文输入法事件
userInput.addEventListener('compositionstart', function () {
    isComposing = true;
});

userInput.addEventListener('compositionend', function () {
    isComposing = false;
    debouncedChangeHandler(); // 中文输入完成，触发变化检测
});